package com.ssm.juc.jmm;

/**
 * 重排序问题
 */
public class ReOrderTest {

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 100000; i++) {
            final ReorderClient client = new ReorderClient();
            Thread t1 = new Thread(new Runnable() {
                public void run() {
                    client.writer();
                }
            });

            Thread t2 = new Thread(new Runnable() {
                public void run() {
                    client.reader();
                }
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

            if (client.j != 0) {
                System.out.println("发生了重排序, client.j=" + client.j);
            }
        }

        System.out.println("the end");
    }

    private static class ReorderClient {

        private boolean flag = false;
        private int value = 0;
        private int j;

        private void writer() {
            flag = true; // C1
            value = 2; // C2
        }

        private void reader() {
            if (!flag) { // C3
                j = value * value; // C4
            }
        }

    }

}

